#include "head.h"

int net_ls(request_t *request, int net_fd) {
    // 打开目录
    char full_path[1024] = {0};
    getcwd(full_path, sizeof(full_path));
    strcat(full_path, "/");
    strcat(full_path, request->user_name);
    strcat(full_path, "/");
    strcat(full_path, request->path);
    // strcat(full_path, request->args);
    printf("%s\n", full_path);

    DIR *dir = opendir(full_path);
    if (dir == NULL) {
        return -1;
    }

    // 读取目录中的文件和子目录并输出到buf中
    struct dirent *entry;
    char buf[1024] = {0};
    int num;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
            // 输出文件名
            // 按照整齐的格式输出到buf中
            sprintf(buf + strlen(buf), "%-20s", entry->d_name);
            num++;
            // strcat(buf, entry->d_name);
            strcat(buf, "\t");
            if (num == 5) {
                strcat(buf, "\n");
                num = 0;
            }
        }
    }

    response_t response;
    memset(&response, 0, sizeof(response));
    if (buf[0] == '\0') {
        strcpy(response.args, "目录为空");
        response.status = 1;
        send(net_fd, &response, sizeof(response), 0);
        closedir(dir);
        return 0;
    }
    response.status = 0;
    strcpy(response.args, buf);
    printf("%s\n", response.args);
    printf("---\n");
    send(net_fd, &response, sizeof(response), 0);
    printf("响应了ls请求\n");
    // 关闭目录
    closedir(dir);
    return 0;
}

// 测试
// int main(void) {
//     request_t request;
//     strcpy(request.path, "/home/anmoxuan/code/disk-project/server");
//     net_ls(&request, 0);
//     return 0;
// }